<template>
  <div>
    <p>新建分类</p>

    <a-input
      placeholder="请输入分类名称"
      v-model:value="state.fenlei"
      style="width: 200px"
    ></a-input>
    <a-button @click="btnFn">确定</a-button>
    <hr />
    <p>分类列表</p>
    <!-- 将state的数据渲染出来 -->
    <div class="content">
      <a-list bordered>
        <a-list-item v-for="(item, index) in state.content" :key="index">
          {{ item.name }} <a-button @click="delFn(index)">删除</a-button>
        </a-list-item>
      </a-list>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import {
  addCategoryApi,
  showCategoryApi,
  deleteCategoryApi,
} from "../utils/api.js";

const state = ref({
  fenlei: "",
  content: [],
});

const btnFn = () => {
  // 将输入框的值添加到state的content数组中
  state.value.content.push(state.value.fenlei);
  // 将state的数据添加到数据库中
  addCategoryApi({ name: state.value.fenlei }).then((res) => {
    console.log(res);
  });

  // 再次调用showCategoryApi()方法，将数据库中的数据渲染到页面上
  showCategoryApi().then((res) => {
    state.value.content = res.data;
  });

  // 清空输入框
  state.value.fenlei = "";
};

// 页面加载时，将数据库中的数据渲染到页面上
showCategoryApi().then((res) => {
  state.value.content = res.data;
});

// 删除分类
const delFn = async (index) => {
  // 弹出框，是否确定删除
  const res = confirm("是否确定删除");
  if (!res) return;

  
  // 获取当前分类的id
  const id = state.value.content[index].id;
  console.log(id);
  // 删除数据库中的数据
  await deleteCategoryApi({ id: id }).then((res) => {
    console.log(res);
  });

  // 删除页面中的数据
  state.value.content.splice(index, 1);
};
</script>
<style lang="less" scoped></style>
